/*****************************************
/*		Javier Barandiaran Martirena	 *
/*				   2002					 *
/*										 *
/* http://www.geocities.com/opengladiator*
/*										 *
/*		Codigo Base Jeff Molofee 		 *
/*		http://nehe.gamedev.net 		 *
/*****************************************/
#include <windows.h>		// Header File For Windows
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library
#include <gl\glaux.h>		// Header File For The Glaux Library
#include <stdarg.h>	
#include <stdio.h>
#include "reloj.h"
#include "texturas.h"

	

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default

int h,f;

const numtext=15;
TexturaTGA *texturas[numtext];

GLuint	base;

int mouse_x, mouse_y;	

reloj *mireloj;

int estado=0;		//textura que se dibuja(boton rojo pulsado,boton verde,...)
					//estado=0 ningun boton iluminado
					//estado=1 boton verde pulsado
					//estado=2 boton rojo pulsado
					//estado=3 boton azul pulsado
					//estado=4 boton amariilo pulsado

float Tultimo=0.0f;			//Tiempo transcurrido desde que se encendio un boton
float Tencendido=950.0f;	//Tiempo que permanece encendido un boton
float Tseparacion=1000;		//Tiempo de separacion entre cada boton
float Trespuesta=3050;		//Tiempo maximo de respuesta para el jugador

int numpulsaciones=0;		//numero de pulsaciones realizadas por el jugador hasta el momento

int secuencia[20];			//array de estados(1,2,3,4), la secuencia de luces
int actual=0;				//elemento actual de la secuencia para cuando se repite
int numgeneradas=0;			//numero de luces generadas hasta el momento

int nivel[6]={8,10,12,14,16,18};	//longitud en numero de luces de cada nivel
int nact=0;					//nivel actual(0,1,2,3)

bool generando=TRUE;	//indica si se esta generando una secuencia 
bool pulsacion=FALSE;	//indica si el jugador a pulsado un boton
bool inicio=TRUE;		//indica si estamos en el menu de inicio
bool salir=FALSE;
bool repit=FALSE;
bool yo=FALSE;
bool mnivel=FALSE;		//indica si estamos en el menu de niveles
bool fallo=FALSE;		//indica si el jugador ha fallado
bool triunfo=FALSE;		//indica si el jugador ha completado la secuencia

typedef struct
{
	int cabecera;
	int opciones;
}Smenu;
Smenu menus[4];			//guarda el ID de la textura para cada menu
						//menus[0]	inicio
						//menus[1]	triunfo
						//menus[2]	fracaso
						//menus[3]	nivel

int botonp;				//que boton del menu esta pulsado


int val;

char *sonidos[5]={"","data\\verde.wav","data\\rojo.wav","data\\azul.wav","data\\amarillo.wav"};

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

GLvoid BuildFont(GLvoid)								// Build Our Bitmap Font
{
	HFONT	font;										// Windows Font ID
	HFONT	oldfont;									// Used For Good House Keeping

	base = glGenLists(96);								// Storage For 96 Characters

	font = CreateFont(	-24,							// alto Of Font
						0,								// ancho Of Font
						0,								// Angle Of Escapement
						0,								// Orientation Angle
						FW_BOLD,						// Font Weight
						FALSE,							// Italic
						FALSE,							// Underline
						FALSE,							// Strikeout
						ANSI_CHARSET,					// Character Set Identifier
						OUT_TT_PRECIS,					// Output Precision
						CLIP_DEFAULT_PRECIS,			// Clipping Precision
						ANTIALIASED_QUALITY,			// Output Quality
						FF_DECORATIVE|VARIABLE_PITCH,		// Family And Pitch
						"Arial");					// Font Name

	oldfont = (HFONT)SelectObject(hDC, font);           // Selects The Font We Want
	wglUseFontBitmaps(hDC, 32, 96, base);				// Builds 96 Characters Starting At Character 32
	SelectObject(hDC, oldfont);							// Selects The Font We Want
	DeleteObject(font);									// Delete The Font
}

GLvoid KillFont(GLvoid)									// Delete The Font List
{
	glDeleteLists(base, 96);							// Delete All 96 Characters
}

GLvoid glPrint(const char *fmt, ...)					// Custom GL "Print" Routine
{
	char		text[256];								// Holds Our String
	va_list		ap;										// Pointer To List Of Arguments

	if (fmt == NULL)									// If There's No Text
		return;											// Do Nothing

	va_start(ap, fmt);									// Parses The String For Variables
	    vsprintf(text, fmt, ap);						// And Converts Symbols To Actual Numbers
	va_end(ap);											// Results Are Stored In Text

	glPushAttrib(GL_LIST_BIT);							// Pushes The Display List Bits
	glListBase(base - 32);								// Sets The Base Character to 32
	glCallLists(strlen(text), GL_UNSIGNED_BYTE, text);	// Draws The Display List Text
	glPopAttrib();										// Pops The Display List Bits
}

GLvoid ReSizeGLScene(GLsizei ancho, GLsizei alto)		// Resize And Initialize The GL Window
{
	if (alto==0)										// Prevent A Divide By Zero By
	{
		alto=1;										// Making alto Equal One
	}

	glViewport(0,0,ancho,alto);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
	//gluPerspective(45.0f,(GLfloat)ancho/(GLfloat)alto,0.1f,100.0f);
	glOrtho(0.0f,ancho,alto,0.0f,-1.0f,1.0f);
	
	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
}

int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
	glShadeModel(GL_FLAT);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glDisable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

	glEnable(GL_TEXTURE_2D);
	
	//glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	BuildFont();

	for(int t=0;t<numtext;t++)
	{
		texturas[t]=(TexturaTGA*)malloc(sizeof(TexturaTGA));
	}

	/*TCHAR pathAplicacion[MAX_PATH];
    GetModuleFileName(NULL, pathAplicacion, MAX_PATH);
    CString nombrePath=pathAplicacion;
    int pos;
    pos=nombrePath.ReverseFind('\\');

    nombrePath=nombrePath.Left(pos+1);
    nombrePath+=_T("\data\simon.tga");*/

	CargaTGA(texturas[0],"data\\simon.tga");
	CargaTGA(texturas[1],"data\\simonv.tga");
	CargaTGA(texturas[2],"data\\simonr.tga");
	CargaTGA(texturas[3],"data\\simonb.tga");
	CargaTGA(texturas[4],"data\\simona.tga");
	//botones
	CargaTGA(texturas[6],"data\\menu.tga");
	
	
	menus[0].opciones=7;
	menus[0].cabecera=11;
	CargaTGA(texturas[11],"data\\men.tga");
	CargaTGA(texturas[7],"data\\Inicio.tga");
	
	menus[1].opciones=8;
	menus[1].cabecera=13;
	CargaTGA(texturas[8],"data\\triunfo.tga");
	CargaTGA(texturas[13],"data\\fel.tga");
	
	menus[2].opciones=9;
	menus[2].cabecera=14;
	CargaTGA(texturas[9],"data\\fallo.tga");
	CargaTGA(texturas[14],"data\\FAL.tga");
	
	menus[3].opciones=10;
	menus[3].cabecera=12;
	CargaTGA(texturas[10],"data\\niveles.tga");
	CargaTGA(texturas[12],"data\\dif.tga");
	
	CargaTGA(texturas[5],"data\\yo.tga");

	srand(mireloj->TimerGetTime());
	
	
	return TRUE;		
}


void ReiniciarJuego(int nact)
{
	inicio=FALSE;
	fallo=FALSE;
	triunfo=FALSE;
	generando=TRUE;
	pulsacion=FALSE;
	numgeneradas=0;
	estado=0;	
	numpulsaciones=0;
	Tencendido=950.0f;
	Tseparacion=1000;
	Trespuesta=3050;
}

int SelecMenu(int mx,int my,int menu)
{
	GLuint alpha,byte,bytepp,alto,ancho;
	int x,y,boton;
	int t=menus[menu].opciones;
	float factorx=300.0f/texturas[t]->ancho;
	float factory=210.0f/texturas[t]->alto;

	
	bytepp=texturas[t]->bpp/8;
	alto=texturas[t]->alto;
	ancho=texturas[t]->ancho;
	x=int((mx-270)/factorx);
	y=int((400-my)/factory);
	boton=-1;
	if(mx>270&& mx<570 && my<400 &&my>190)
	{
		if(mnivel)
		{
			if(mx<420)
			{
				if(my<260)
					boton=0;
				else
				{
					if(my<330)
						boton=1;
					else
						boton=2;
				}
			}
			else
			{
				if(my<260)
					boton=3;
				else
				{
					if(my<330)
						boton=4;
					else
						boton=5;
				}
			}
		}	
		else
		{
			if(my<260)
				boton=0;
			else
			{
				if(my<330)
					boton=1;
				else
					boton=2;
			}
		}
		
		if(boton!=-1||yo)
		{
			byte=bytepp-1+((y*ancho)+x)*bytepp;
			alpha=texturas[t]->imageData[byte];	
			if (alpha!=0)
			{
				if(yo)
					return 1;
				return boton;
			}
		}
	}
	return -1;
}

void MostrarMenu(int menu)
{

	int t=menus[menu].opciones;
	glEnable(GL_BLEND);
	glBindTexture(GL_TEXTURE_2D, texturas[menus[menu].cabecera]->texID);
	glBegin(GL_QUADS);
		glTexCoord2d(1,0);
		glVertex2d(590,190);	
		glTexCoord2d(1,1);
		glVertex2d(590,130);
		glTexCoord2d(0,1);	
		glVertex2d(250,130);
		glTexCoord2d(0,0);
		glVertex2d(250,190);	
	glEnd();
	glBindTexture(GL_TEXTURE_2D, texturas[6]->texID);
	glBegin(GL_QUADS);
		glTexCoord2d(1,0);
		glVertex2d(570,400);	
		glTexCoord2d(1,1);
		glVertex2d(570,190);
		glTexCoord2d(0,1);	
		glVertex2d(270,190);
		glTexCoord2d(0,0);
		glVertex2d(270,400);	
	glEnd();
	
	glBindTexture(GL_TEXTURE_2D, texturas[t]->texID);
	glBegin(GL_QUADS);
		glTexCoord2d(1,0);
		glVertex2d(570,400);	
		glTexCoord2d(1,1);
		glVertex2d(570,190);
		glTexCoord2d(0,1);	
		glVertex2d(270,190);
		glTexCoord2d(0,0);
		glVertex2d(270,400);	
	glEnd();
	glDisable(GL_BLEND);
}

bool boton(int mx, int my)
{
	GLuint alpha,byte,bytepp,alto,ancho;
	int x,y;
	float factorx=800.0/texturas[0]->ancho;
	float factory=600.0/texturas[0]->alto;
			
	//acierto: si el impacto esta en el cuadrado y el pixel alpha
	//de la textura no es negro
	bytepp=texturas[0]->bpp/8;
	alto=texturas[0]->alto;
	ancho=texturas[0]->ancho;
	x=int(mx/factorx);
	y=int((600-my)/factory);
	byte=bytepp-1+((y*ancho)+x)*bytepp;
	alpha=texturas[0]->imageData[byte];	
	if (alpha!=0)
	{
		return true;
	}
	return false;
}

void Pulsa(int mx,int my)
{
	if (boton(mx,my))
	{
		
		pulsacion=TRUE;

		if(mx<400)
		{
			if(my>300)
			{
				estado=4;
			}
			else
				estado=1;
			}
			else
			{
				if(my>300)
					estado=3;
				else
					estado=2;
			}		
		}
		else
			estado=0;
}
void RecibiendoSecuencia()
{
	if(pulsacion)					//SI HAY PULSACION
	{
		pulsacion=FALSE;
		if(estado!=secuencia[numpulsaciones])	//SI NO COINCIDE
		{
			fallo=TRUE;
			PlaySound("data\\error2.wav",NULL,0);
		}
		else									//COINCIDE
		{
			PlaySound(sonidos[estado],NULL,1);
			numpulsaciones++;
			Tultimo=mireloj->TimerGetTime();
		}
	}
	else 
	{
		if ((mireloj->TimerGetTime()-Tultimo)>Tencendido)
		{
			estado=0;
		}
		if ((mireloj->TimerGetTime()-Tultimo)>Trespuesta)	//SI SE HA PASADO EL TIEMPO DE RESPUESTA
		{
			fallo=TRUE;
			PlaySound("data\\error2.wav",NULL,0);
		}	
	}
}

void Repetir()
{
		if ((mireloj->TimerGetTime()-Tultimo)>Tseparacion)
		{
			estado=secuencia[actual];
			PlaySound(sonidos[estado],NULL,1);
			actual++;
			Tultimo=mireloj->TimerGetTime();
		}
		else if ((mireloj->TimerGetTime()-Tultimo)>Tencendido)
			estado=0;
}

void Generar()
{
	if(actual<numgeneradas)			//REPETIMOS LA SECUENCIA GENERADA
	{
		Repetir();
	}
	else					
	{
		if ((mireloj->TimerGetTime()-Tultimo)>Tseparacion) //GENERAMOS UNO MAS
		{

			//
			val=1+rand()%4;
			estado=val;
			PlaySound(sonidos[estado],NULL,1);
			Tultimo=mireloj->TimerGetTime();
			secuencia[numgeneradas]=estado;
			numgeneradas++;
			actual=0;
			generando=FALSE;
			//Reducimos los tiempos
			//Trespuesta-=50;
			Tencendido-=100.0;
			Tseparacion-=100.0;
			if(Tseparacion<=200.0)
			{
				Tseparacion=200.0;
			}
			if(Tencendido<=150.0)
			{
				Tencendido=150.0;
			}

		}
		else if ((mireloj->TimerGetTime()-Tultimo)>Tencendido)
			estado=0;		
	}
}

int DrawGLScene(GLvoid)							
{	
	glClear(GL_COLOR_BUFFER_BIT);	
	glLoadIdentity();
	if(inicio)
		MostrarMenu(0);
	else if (mnivel)
	{
		MostrarMenu(3);
	}
	else if(yo)
	{
		glBindTexture(GL_TEXTURE_2D, texturas[5]->texID);
		glBegin(GL_TRIANGLE_STRIP);
				glTexCoord2d(0,0);
			glVertex2d(0,599);	
				glTexCoord2d(0,1);	
			glVertex2d(0,0);
				glTexCoord2d(1,0);
			glVertex2d(799,599);
				glTexCoord2d(1,1);
			glVertex2d(799,0);
		glEnd();
	}
	
	else
	{
		if(repit)
		{	
			Repetir();
			if(actual==numgeneradas)
			{
				repit=FALSE;
				fallo=TRUE;
			}
		}
		if(generando)	//GENERANDO SECUENCIA
			Generar();
		else		//LA SECUENCIA HA SIDO GENERADA
		{
			if(!fallo && !triunfo)
			{
				if(numpulsaciones<numgeneradas)		//TODAVIA FALTAN PULSACIONES
				{
					RecibiendoSecuencia();	
				}
				else			//YA SE HA PULSADO TODA LA SECUENCIA
				{
					
					if(numpulsaciones==nivel[nact])	//SE HA COMPLETADO EL NIVEL
					{
						triunfo=TRUE;
						PlaySound("data\\TRIUNFO.WAV",NULL,0);
					}
					else							//TODAVIA NO SE HA COMPLETADO EL NIVEL
					{
						generando=TRUE;
						srand(mireloj->TimerGetTime());
						numpulsaciones=0;				
					}
				}
			}
		}
			
		glBindTexture(GL_TEXTURE_2D, texturas[estado]->texID);
		glBegin(GL_TRIANGLE_STRIP);
				glTexCoord2d(0,0);
			glVertex2d(0,599);	
				glTexCoord2d(0,1);	
			glVertex2d(0,0);
				glTexCoord2d(1,0);
			glVertex2d(799,599);
				glTexCoord2d(1,1);
			glVertex2d(799,0);
		glEnd();
		
		if(fallo)
		{
			if ((mireloj->TimerGetTime()-Tultimo)>200)
			{
				estado++;
				if(estado==5)
					estado=1;
				Tultimo=mireloj->TimerGetTime();
			}
			MostrarMenu(2);
		}
		if(triunfo)
		{
			if ((mireloj->TimerGetTime()-Tultimo)>100)
			{
				estado++;
				if(estado>=5)
					estado=1;
				Tultimo=mireloj->TimerGetTime();
			}
			MostrarMenu(1);
		}
		/*glLineWidth(1.0);
		glBegin(GL_LINES);
		glColor3f(1.0,0.0,0.0);
			glVertex2f((float)mouse_x-10.0f,(float)mouse_y);
			glVertex2f((float)mouse_x+10.0f,(float)mouse_y);
			glVertex2f((float)mouse_x,(float)mouse_y-5.0f);
			glVertex2f((float)mouse_x,(float)mouse_y+5.0f);
		glEnd();*/
		glColor4f(1.0,0.0,0.0,1.0);
		/*glRasterPos2f(25,300);
		glPrint("Separacion %f",Tseparacion);
		glRasterPos2f(25,400);
		glPrint("Encendido %f",Tencendido);*/
		glDisable(GL_BLEND);
		glRasterPos2f(25,550);
		glPrint("Level %d",nact);
		glColor4f(1.0,1.0,1.0,1.0);
	}
	
	


	return TRUE;										// Everything Went OK
}

GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{
	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}

	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	ancho			- ancho Of The GL Window Or Fullscreen Mode				*
 *	alto			- alto Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int ancho, int alto, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)ancho;		// Set Right Value To Requested ancho
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)alto;		// Set Bottom Value To Requested alto

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= ancho;				// Selected Screen ancho
		dmScreenSettings.dmPelsHeight	= alto;				// Selected Screen alto
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window ancho
								WindowRect.bottom-WindowRect.top,	// Calculate Window alto
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(ancho, alto);					// Set Up Our Perspective GL Screen

	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}

LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				active=TRUE;						// Program Is Active
			}
			else
			{
				active=FALSE;						// Program Is No Longer Active
			}

			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:							// Intercept System Commands
		{
			switch (wParam)							// Check System Calls
			{
				case SC_SCREENSAVE:					// Screensaver Trying To Start?
				case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
				return 0;							// Prevent From Happening
			}
			break;									// Exit
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			keys[wParam] = TRUE;					// If So, Mark It As TRUE
			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			keys[wParam] = FALSE;					// If So, Mark It As FALSE
			return 0;								// Jump Back
		}

		case WM_SIZE:								// Resize The OpenGL Window
		{
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=ancho, HiWord=alto
			return 0;								// Jump Back
		}
		/*case WM_LBUTTONUP:
		{
			botonp=-1;
		}*/
		case WM_LBUTTONDOWN:
			{
	            mouse_x = LOWORD(lParam);          
				mouse_y = HIWORD(lParam);
				
				if(!generando&&!pulsacion&&!fallo&&!triunfo&&!inicio)
					Pulsa(mouse_x,mouse_y);
				else if(inicio)
				{
					
					botonp=SelecMenu(mouse_x,mouse_y,0);
					if(botonp!=-1)
						PlaySound("data\\boton.WAV",NULL,1);
					switch(botonp)
					{
					case 0:{mnivel=TRUE;
							inicio=FALSE;
						   }
						break;
					case 1:{
							yo=TRUE;
							inicio=FALSE;
						   }

						break;
					case 2:salir=TRUE;
						break;
					default:
						break;
					}
				}
				else if(mnivel)
				{
					
					botonp=SelecMenu(mouse_x,mouse_y,3);
					if(botonp!=-1)
					{
						PlaySound("data\\boton.WAV",NULL,1);
						nact=botonp;
						mnivel=FALSE;
						ReiniciarJuego(nact);
					}
				}
				else if(fallo)
				{
					
					botonp=SelecMenu(mouse_x,mouse_y,0);
					if(botonp!=-1)
						PlaySound("data\\boton.WAV",NULL,1);
					switch(botonp)
					{
					case 0:ReiniciarJuego(nact);
						break;
					case 1:{inicio=TRUE;
							fallo=FALSE;
						   }
						break;
					case 2:{fallo=FALSE;
							actual=0;
							repit=TRUE;
						   }
						break;
					default:
						break;
					}
				}
				else if(yo)
				{
					yo=FALSE;
					inicio=TRUE;
				}

				if(triunfo)
				{
					botonp=SelecMenu(mouse_x,mouse_y,0);
					if(botonp!=-1)
						PlaySound("data\\boton.WAV",NULL,1);
					switch(botonp)
					{
					case 0:{
							nact++;
							if(nact==6)
								salir=TRUE;
							else
								ReiniciarJuego(nact);
						   }
						break;
					case 1:{
						inicio=TRUE;
						triunfo=FALSE;
						   }
						break;
					case 2:salir=TRUE;
						break;
					default:
						break;
					}
				}

			}
		break;

		case WM_MOUSEMOVE:
			{
	            mouse_x = LOWORD(lParam);          
				mouse_y = HIWORD(lParam);
			}
		break;
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop
	

	
	// Ask The User Which Screen Mode They Prefer
	/*if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}*/

	mireloj=new reloj;
	//ShowCursor(FALSE);
	//GLint	viewport[4];
	//glGetIntegerv(GL_VIEWPORT, viewport);
	//SetCursorPos(viewport[2]/2,viewport[3]/2);
	// Create Our OpenGL Window
	fullscreen=TRUE;
	if (!CreateGLWindow("Simon",800,600,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}
	
					
	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if (active)								// Program Active?
			{
				if (keys[VK_ESCAPE])				// Was ESC Pressed?
				{
					done=TRUE;						// ESC Signalled A Quit
				}
				else								// Not Time To Quit, Update Screen
				{				
					if(salir)
						done=TRUE;
					DrawGLScene();					// Draw The Scene
					SwapBuffers(hDC);				// Swap Buffers (Double Buffering)
				}
			}					
			
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}



